package com.vueblog.service.impl;

import com.vueblog.dao.BlogDao;
import com.vueblog.dao.CommentDao;
import com.vueblog.po.Comment;
import com.vueblog.service.CommentService;
import org.springframework.aop.framework.AopConfigException;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private CommentDao commentDao;

    @Autowired
    private BlogDao blogDao;

    private List<Comment> replyComment=new ArrayList<>();

    @Override
    public List<Comment> listCommentByBlogId(int blogId) {
        List<Comment> rootComments =  commentDao.listCommentByBlogIdAndParentCommentId(blogId,-1);
        for (Comment rootComment : rootComments) {
            listChildrenComment(blogId,rootComment);
            rootComment.setReplyComments(replyComment);
            replyComment = new ArrayList<>();
        }
        return rootComments;
    }

    @Override
    @Transactional
    public int saveComment(Comment comment) {
        comment.setCreateTime(new Date());
        blogDao.updateCommentCount(1,comment.getBlogId());
        return commentDao.saveComment(comment);
    }

    private void listChildrenComment(int blogId,Comment parentComment){
        List<Comment> childrenComments = commentDao.listCommentByBlogIdAndParentCommentId(blogId,parentComment.getId());
        if (childrenComments.size()>0){
            for (Comment childrenComment : childrenComments) {
                replyComment.add(childrenComment);
                listChildrenComment(blogId,childrenComment);
            }
        }
    }

    @Override
    @Transactional
    public int deleteComment(int commentId) {
        Comment comment=commentDao.findCommentById(commentId);
        blogDao.updateCommentCount(-1,comment.getBlogId());
        return commentDao.deleteComment(commentId);
    }
}
